/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.service.datasource.stat;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import ch.qos.logback.core.util.FileSize;

/**
 * druid统计日志类
 *
 * @author yoara
 */
public class LoggerUtil {
    /**
     * 自定义logger生成器，
     * @param defLevel 默认日志级别
     * @param baseDir 日志基本目录
     * @param logName 日志文件名称
     * @param clazz 日志的clazz
     * @return 日志对象
     */
    public static org.slf4j.Logger getLogger(final String defFormat,final String defLevel,
                                             final String defSize, final String baseDir,
                                             final String logName, Class<?> clazz) {
        Logger logger = new LoggerContext().getLogger(clazz);
        final LoggerContext loggerContext = logger.getLoggerContext();
        loggerContext.start();
        RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>(){{
            setContext(loggerContext);
            setFile(baseDir + "/" + logName + ".log");

            PatternLayoutEncoder encoder = new PatternLayoutEncoder(){{
                setContext(loggerContext);
                setPattern(defFormat);
            }};
            encoder.start();

            TimeBasedRollingPolicy timeBasedRollingPolicy = new TimeBasedRollingPolicy(){{
                setContext(loggerContext);
                setFileNamePattern(baseDir + "/" + logName + "-%d{yyyyMMdd}.%i.log");

                setTimeBasedFileNamingAndTriggeringPolicy(new SizeAndTimeBasedFNATP() {{
                    setContext(loggerContext);
                    setMaxFileSize(FileSize.valueOf(defSize));
                }});
            }};
            timeBasedRollingPolicy.setParent(this);
            timeBasedRollingPolicy.start();

            setRollingPolicy(timeBasedRollingPolicy);
            setEncoder(encoder);
        }};
        appender.start();


        logger.setAdditive(false);
        logger.setLevel(Level.valueOf(defLevel));
        logger.addAppender(appender);
		return logger;
    }

    private LoggerUtil(){}
}
